package cn.harry.cabinet.view.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.OperationLog
import cn.harry.cabinet.constants.OperationLogConstants
import java.text.SimpleDateFormat
import java.util.*

/**
 * 操作日志列表适配器
 */
class OperationLogAdapter(
    private val onItemClick: (OperationLog) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        private const val VIEW_TYPE_LOG = 0
        private const val VIEW_TYPE_LOAD_MORE = 1
    }

    private var logs: List<OperationLog> = emptyList()
    private var showLoadMore = false
    private var isLoadingMore = false
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    @SuppressLint("NotifyDataSetChanged")
    fun setLogs(newLogs: List<OperationLog>) {
        logs = newLogs
        notifyDataSetChanged()
    }
    
    fun appendLogs(newLogs: List<OperationLog>) {
        val oldSize = logs.size
        logs = logs + newLogs
        notifyItemRangeInserted(oldSize, newLogs.size)
    }
    
    fun getLogs(): List<OperationLog> = logs

    fun setShowLoadMore(show: Boolean) {
        if (showLoadMore != show) {
            showLoadMore = show
            if (show) {
                notifyItemInserted(itemCount - 1)
            } else {
                notifyItemRemoved(itemCount)
            }
        }
    }

    fun setLoadingMore(loading: Boolean) {
        isLoadingMore = loading
        if (showLoadMore) {
            notifyItemChanged(itemCount - 1)
        }
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == logs.size && showLoadMore) VIEW_TYPE_LOAD_MORE else VIEW_TYPE_LOG
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_LOG -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_operation_log, parent, false)
                LogViewHolder(view)
            }
            VIEW_TYPE_LOAD_MORE -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_load_more, parent, false)
                LoadMoreViewHolder(view)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is LogViewHolder -> holder.bind(logs[position])
            is LoadMoreViewHolder -> holder.bind()
        }
    }

    override fun getItemCount(): Int = logs.size + if (showLoadMore) 1 else 0

    inner class LogViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val tvTimestamp: TextView = itemView.findViewById(R.id.tvTimestamp)
        private val tvOperationType: TextView = itemView.findViewById(R.id.tvOperationType)
        private val tvResult: TextView = itemView.findViewById(R.id.tvResult)
        private val tvDescription: TextView = itemView.findViewById(R.id.tvDescription)
        private val tvOperator: TextView = itemView.findViewById(R.id.tvOperator)
        private val tvTarget: TextView = itemView.findViewById(R.id.tvTarget)

        fun bind(log: OperationLog) {
            // 时间
            tvTimestamp.text = dateFormat.format(Date(log.timestamp))

            // 操作类型
            val typeText = getOperationTypeText(log.operationType)
            val subTypeText = if (log.operationSubType != null) {
                " - ${getOperationSubTypeText(log.operationSubType)}"
            } else ""
            tvOperationType.text = "$typeText$subTypeText"

            // 结果
            tvResult.text = getResultText(log.result)
            tvResult.setTextColor(getResultColor(log.result))

            // 描述
            tvDescription.text = log.description

            // 操作人
            if (log.operatorName != null) {
                tvOperator.visibility = View.VISIBLE
                val operatorText = buildString {
                    append(log.operatorName)
                    if (log.operatorEmployeeId != null) {
                        append(" (${log.operatorEmployeeId})")
                    }
                }
                tvOperator.text = "操作人: $operatorText"
            } else {
                tvOperator.visibility = View.GONE
            }

            // 目标对象
            if (log.targetName != null) {
                tvTarget.visibility = View.VISIBLE
                val targetText = buildString {
                    if (log.targetType != null) {
                        append(getTargetTypeText(log.targetType))
                        append(": ")
                    }
                    append(log.targetName)
                }
                tvTarget.text = targetText
            } else {
                tvTarget.visibility = View.GONE
            }

            itemView.setOnClickListener { onItemClick(log) }
        }

        private fun getOperationTypeText(type: String): String {
            return when (type) {
                OperationLogConstants.OperationType.USER_AUTH -> "用户认证"
                OperationLogConstants.OperationType.INSTRUMENT_TAKE -> "取仪器"
                OperationLogConstants.OperationType.INSTRUMENT_RETURN -> "还仪器"
                OperationLogConstants.OperationType.DATA_SYNC -> "数据同步"
                OperationLogConstants.OperationType.API_CALL -> "接口调用"
                OperationLogConstants.OperationType.CONFIG_CHANGE -> "配置修改"
                OperationLogConstants.OperationType.SCHEDULED_TASK -> "定时任务"
                OperationLogConstants.OperationType.SYSTEM_EVENT -> "系统事件"
                else -> type
            }
        }

        private fun getOperationSubTypeText(subType: String): String {
            return when (subType) {
                OperationLogConstants.OperationSubType.FACE_RECOGNITION -> "人脸识别"
                OperationLogConstants.OperationSubType.CARD_SCAN -> "刷卡"
                OperationLogConstants.OperationSubType.PASSWORD_AUTH -> "密码认证"
                OperationLogConstants.OperationSubType.PUSH_TO_SERVER -> "推送到服务器"
                OperationLogConstants.OperationSubType.PULL_FROM_SERVER -> "从服务器拉取"
                OperationLogConstants.OperationSubType.THEME_CHANGE -> "主题切换"
                OperationLogConstants.OperationSubType.PASSWORD_CHANGE -> "密码修改"
                OperationLogConstants.OperationSubType.NETWORK_CONFIG -> "网络配置"
                OperationLogConstants.OperationSubType.FACE_CONFIG -> "人脸配置"
                OperationLogConstants.OperationSubType.CABINET_CONFIG -> "柜子配置"
                "HOME_CONFIG" -> "首页配置"
                OperationLogConstants.OperationSubType.AUTO_SYNC -> "自动同步"
                OperationLogConstants.OperationSubType.AUTO_CLEANUP -> "自动清理"
                OperationLogConstants.OperationSubType.AUTO_BACKUP -> "自动备份"
                else -> subType
            }
        }

        private fun getResultText(result: String): String {
            return when (result) {
                OperationLogConstants.Result.SUCCESS -> "成功"
                OperationLogConstants.Result.FAILED -> "失败"
                OperationLogConstants.Result.PENDING -> "进行中"
                else -> result
            }
        }

        private fun getResultColor(result: String): Int {
            return when (result) {
                OperationLogConstants.Result.SUCCESS -> 0xFF4CAF50.toInt() // 绿色
                OperationLogConstants.Result.FAILED -> 0xFFF44336.toInt() // 红色
                OperationLogConstants.Result.PENDING -> 0xFFFF9800.toInt() // 橙色
                else -> 0xFF757575.toInt() // 灰色
            }
        }

        private fun getTargetTypeText(targetType: String): String {
            return when (targetType) {
                OperationLogConstants.TargetType.CABINET -> "柜子"
                OperationLogConstants.TargetType.USER -> "用户"
                OperationLogConstants.TargetType.CONFIG -> "配置"
                OperationLogConstants.TargetType.INSTRUMENT -> "仪器"
                OperationLogConstants.TargetType.SYSTEM -> "系统"
                else -> targetType
            }
        }
    }

    inner class LoadMoreViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind() {
            val loadMoreText = itemView.findViewById<TextView>(R.id.loadMoreText)
            val loadMoreProgress = itemView.findViewById<View>(R.id.loadMoreProgress)

            if (isLoadingMore) {
                loadMoreText.text = "数据加载中..."
                loadMoreProgress.visibility = View.VISIBLE
                itemView.isClickable = false
                itemView.alpha = 0.7f
            } else {
                loadMoreText.text = "点击加载更多"
                loadMoreProgress.visibility = View.GONE
                itemView.isClickable = true
                itemView.alpha = 1.0f
            }
        }
    }
}
